package elephant.servers.gameserver.core;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import elephant.servers.gameserver.session.GameSession;
import elephant.servers.gameserver.session.GameSessionManager;

/**
 * 
 * @author icecooly
 *
 */
public class GameRoom {
	private String id;
	private Map<String,GameSession>sessions;
	private long createTime;
	private GameSessionManager sessionManager;
	private Object userObject;
	public GameRoom(String id,GameSessionManager sessionManager) {
		this.id=id;
		this.sessionManager=sessionManager;
		this.sessions=new ConcurrentHashMap<>();
		createTime=System.currentTimeMillis();
	}
	/* 
	 *
	 */
	public String getId(){
		return id;
	}
	
	/* 
	 *
	 */
	public void addSession(GameSession session){
		if(session.getPrincipal()==null){
			throw new IllegalArgumentException("principal can not be null.");
		}
		session.joinRoom(this);
		sessions.put(session.getPrincipal(),session);
	}
	/* 
	 *
	 */
	
	public GameSession removeSession(String principal){
		GameSession s=sessions.remove(principal);
		if(s!=null){
			s.leaveRoom(this);
		}
		return s;
	}
	
	public GameSession removeSession(GameSession session){
		GameSession s=sessions.remove(session.getPrincipal());
		if(s!=null){
			s.leaveRoom(this);
		}
		return s;
	}
	/* 
	 *
	 */
	
	public List<GameSession>removeAllSessions(){
		List<GameSession>allSessions=new ArrayList<>(sessions.values());
		for(GameSession s:allSessions){
			s.leaveRoom(this);
		}
		sessions.clear();
		return allSessions;
	}
	/* 
	 *
	 */
	
	public List<GameSession>getSessions(){
		List<GameSession>allSessions=new ArrayList<>(sessions.values());
		return allSessions;
	}
	/* 
	 *
	 */
	
	public GameSession getSessionByPrincipal(String principal){
		if(principal==null){
			throw new IllegalArgumentException("principal can not be null.");
		}
		return sessions.get(principal);
	}
	/* 
	 *
	 */
	
	public void destroy(){
		removeAllSessions();
		sessionManager.removeRoom(id);
	}
	/* 
	 *
	 */
	
	public long getCreateTime(){
		return createTime;
	}
	/* 
	 *
	 */
	
	public void broadcast(String serviceId,Object payload){
		for(GameSession session:sessions.values()){
			if(session.isActive()){
				session.push(serviceId, payload);
			}
		}
	}
	/* 
	 *
	 */
	
	public void broadcast(String serviceId,Object payload,Set<String>blockPrincipalSet){
		for(GameSession session:sessions.values()){
			if(session.isActive()){
				if(!blockPrincipalSet.contains(session.getPrincipal())){
					session.push(serviceId, payload);
				}
			}
		}	
	}
	/* 
	 *
	 */
	
	public Object getUserObject() {
		return userObject;
	}
	/* 
	 *
	 */
	
	public void setUserObject(Object userObject) {
		this.userObject = userObject;
	}
	
}
